package com.wzqj.agent.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.common.ConfigHelper;
import com.wzqj.agent.common.JsonOutput;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.constant.WebConstant;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.AgentService;
import com.wzqj.agent.web.service.StoreService;
import com.wzqj.agent.web.service.UserService;
import com.wzqj.web.http.CookieUtils;
import com.wzqj.wsp.config.Config;
import com.wzqj.wsp.http.HttpUtil;
/**
 * 店铺Controller
 * @author gz
 *
 */
@Controller
@RequestMapping("/store")
public class StoreWebController {

	@Autowired
	private UserService userService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private AgentService agentService;
	/**
	 * 认领审核状态，默认为1
		1 未审核
		2 审核通过
		3 审核失败
	 */
	private static final String CLAIM_STATUS = "2";
	/**
	 * 店铺信息展示页面
	 * @param storeId
	 * @param mcode
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping("/storeInfo")
	public ModelAndView storeInfo(String storeId,String mcode,
			HttpServletRequest request, ModelMap data){
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			Integer userId = Integer.parseInt(userToken);
	        
			//获取用户信息
			User user  = userService.getById(userId);
			data.put("user", user);
			//获取店铺信息
			JSONObject store = storeService.getStoreByStoreId(storeId);
			
			System.out.println("----storeInfo:"+store);
			data.put("store", store);
			rv = "/user/merchant/storeInfo";
			
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		return new ModelAndView(rv, data);
	}
	/**
	 * 跳转到修改店铺信息页面
	 * @param storeId
	 * @param data
	 * @return
	 */
	@RequestMapping("/toEdit")
	public ModelAndView toEdit(String storeId,
			HttpServletRequest request,ModelMap data){
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			Integer userId = Integer.parseInt(userToken);
	        
			//获取用户信息
			User user  = userService.getById(userId);
			data.put("user", user);
			//获取店铺信息
			JSONObject store = storeService.getStoreByStoreId(storeId);
			
			//System.out.println("----storeInfo:"+store);
			data.put("store", store);
			data.put("aliyunUrl", ConfigHelper.getProperty("ALIYUN_URL"));
			rv="/user/merchant/storeInfoEdit";
			
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		return new ModelAndView(rv,data);
	}

	/**
	 * 跳转到添加店铺页面1
	 * @param qualificationId
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping("/toAdd")
	public ModelAndView toAddStore(String qualificationId ,HttpServletRequest request ,ModelMap data){
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			//获取用户信息
			Integer userId = Integer.parseInt(userToken);
			User user  = userService.getById(userId);
			data.put("user", user);
			data.put("qualificationId", qualificationId);
			
			rv = "/user/merchant/addStore1";
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		return new ModelAndView(rv,data);
	}
	
	/**
	 * 获取接口门店信息（长沙接口）
	 * @param shopName
	 * @param city
	 * @param lastId
	 * @param start
	 * @param limit
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping("/doSearch")
	@ResponseBody
	public JSONObject doSearch(
			@RequestParam(value = "shopName", required = true, defaultValue = "") String shopName,
			@RequestParam(value = "city", required = true, defaultValue = "北京") String city,
			@RequestParam(value = "lastId", required = true, defaultValue = "") String lastId,
			@RequestParam(value = "pageIndex", required = true, defaultValue = "1") int pageIndex,
			@RequestParam(value = "limit", required = true, defaultValue = "8") int limit,
			HttpServletRequest req, HttpServletResponse res) {
		String rv = "";
		try{
			 rv = storeService.doSearch(shopName, city, lastId, pageIndex, limit);
		}catch(Exception e){
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		System.out.println("doSearch:"+rv);
		return JSONObject.parseObject(rv);
	}
	
	/**
	 * 百度门店添加
	 * @param baiduId
	 * @param from
	 * @param req
	 * @param data
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addByBaidu")
	public ModelAndView preview(
			@RequestParam(value = "uid", required = false) String baidUid,
			@RequestParam(value = "from", required = false, defaultValue = "add") String from,
			String qualificationId,
			HttpServletRequest request, ModelMap data) throws Exception {
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			Integer userId = Integer.parseInt(userToken);
	        
			//获取用户信息
			User user  = userService.getById(userId);
			data.put("user", user);
			data.put("from", from);
			JSONArray bizClassify = storeService.getBizClassifyList();
			data.put("bizClassify", bizClassify);
			String baiduKey = ConfigHelper.getProperty("BAIDU_KEY");
			data.put("baiduKey", baiduKey);
			data.put("baidUid",baidUid);
			data.put("qualificationId", qualificationId);
			rv = "/user/merchant/addStore2";
			
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}

		return new ModelAndView(rv, data);
	}
	/**
	 * 绑定店铺到商户
	 * @param qualificationId
	 * @param storeId
	 * @param mcode
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping("/bind")
	@ResponseBody
	public JSONObject bind(
			@RequestParam(value = "qualificationId", required = true, defaultValue = "")String qualificationId,
			@RequestParam(value = "storeId", required = true, defaultValue = "")String storeId ,
			@RequestParam(value = "mcode", required = true, defaultValue = "")String mcode,
			@RequestParam(value = "claimStatus", required = true, defaultValue = "2")String claimStatus,
			HttpServletRequest request
			){
		JSONObject data = new JSONObject();
		try {
			JSONObject rv = storeService.bind(qualificationId, storeId, mcode, claimStatus);
			if (rv!=null) {
				data.put("status", 0);
				data.put("info", "绑定成功");
				
			}else{
				data.put("status", 1);
				data.put("info", "绑定失败");
			}
		} catch (Exception e) {
			data.put("status", 1);
			data.put("info", "绑定失败");
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 获取省市区三级联动信息
	 * @param prov
	 * @param request
	 * @return
	 */
	@RequestMapping("/authorZone")
	@ResponseBody
	public JSONObject authorZone(String key1,String value1,String key2,String value2,String url,HttpServletRequest request,ModelMap map,HttpSession session){
		JSONObject params = new JSONObject();
		params.put(key1, value1);
		params.put(key2, value2);
		String result = HttpUtil.getResult(url, params, true);
		JSONObject data = JSONObject.parseObject(result);
		return data;
	};
	/**
     * 获取行业列表（新）
     * @return
     */
    @RequestMapping("/getBizClassifyList")
    @ResponseBody
    public JSONObject getBizClassifyList(){
    	JsonOutput output = new JsonOutput();
        JSONArray data = storeService.getBizClassifyList();
        if(data != null){
            output.setData(data);
        }else{
            output.setErrCode(BusinessErrorType.MERCHANT_STORE_BIZCLASSIFY_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.MERCHANT_STORE_BIZCLASSIFY_ERROR.getErrMsg());
        }
        return output.toJSONObject();
    }
	/**
	 * 门店预览
	 * @param request
	 * @param data
	 * @return
	 */
	@RequestMapping("/preview")
	public ModelAndView preview(HttpServletRequest request , ModelMap data){
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			//获取用户信息
			Integer userId = Integer.parseInt(userToken);
			User user  = userService.getById(userId);
			data.put("user", user);
			
			JSONObject store = new JSONObject();
			//资质id
			String qualificationId = request.getParameter("qualificationId");
			data.put("qualificationId", qualificationId);
			//百度Uid
			String baidUid = request.getParameter("baidUid");
			store.put("baidUid", baidUid);
			
			String from = request.getParameter("from");
			store.put("from", from);
			//店铺信息
			String shopName = request.getParameter("name");
			store.put("name", shopName);
			
			String shopPhone = request.getParameter("tel");
			store.put("tel", shopPhone);
			
			//地址
			String province = request.getParameter("province");
			store.put("province", province);
			String city = request.getParameter("city");
			store.put("city", city);
			
			String area = request.getParameter("area");
			store.put("area", area);
			//百度地图
			String uid = request.getParameter("uid");
			store.put("uid", uid);
			
			String lat = request.getParameter("lat");
			store.put("lat", lat);
			
			String lng = request.getParameter("lng");
			store.put("lng", lng);
			
			String addressDetail = request.getParameter("addressDetail");
			store.put("address_detail", addressDetail);
			//行业信息
			String level1 = request.getParameter("level1");
			store.put("level1", level1);
			String level2 = request.getParameter("level2");
			store.put("level2", level2);
			String level3 = request.getParameter("level3");
			store.put("level3", level3);
			String bizClassify1 = request.getParameter("bizClassify1");
			store.put("bizClassify1", bizClassify1);
			
			String bizClassify2 = request.getParameter("bizClassify2");
			store.put("bizClassify2", bizClassify2);
			String bizClassify3 = request.getParameter("bizClassify3");
			store.put("bizClassify3", bizClassify3);
			String bizClassifyNames =  bizClassify1+bizClassify2+bizClassify3;
			store.put("bizClassifyNames", bizClassifyNames);
			JSONObject bizClassify = new JSONObject();
			bizClassify.put("id", level1);
			bizClassify.put("name", bizClassify1);
			bizClassify.put("level", 1);
			JSONObject b2 = new JSONObject();
			b2.put("id", level2);
			b2.put("name", bizClassify2);
			b2.put("level", 2);
			JSONObject b3 = new JSONObject();
			b3.put("id", level3);
			b3.put("name", bizClassify3);
			b3.put("level", 3);
			if (level3!=null&&!level3.equals("")) {
				b2.put("childClassify", b3);
			}
			bizClassify.put("childClassify", b2);
			store.put("bizClassify", bizClassify);
		
			//联系人信息
			String contactName = request.getParameter("contactName");
			store.put("contactName", contactName);
			
			String contactPhone = request.getParameter("contactPhone");
			store.put("contactPhone", contactPhone);
			//店铺照片
			String busImg = request.getParameter("busImg");
			store.put("busImg", busImg);
			
			String shopImg = request.getParameter("shopImg");
			store.put("shopImg", shopImg);
			
			data.put("store", store);
			System.out.println("preview--data:"+data.toString());
			rv = "/user/merchant/addStore3";
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		return new ModelAndView(rv, data);
	}
	/**
	 * 添加并绑定店铺到商户
	 * @param request
	 * @return
	 */
	@RequestMapping("/addAndBind")
	@ResponseBody
	public JSONObject addAndBind(Integer userId,String qualificationId,
			String baiduUid,
			String name,String tel,
			String provice,String city,String area,String address_detail,String lat,String lng,
			String id1,String bizClassify1,String id2,String bizClassify2,String id3,String bizClassify3,
			String contactName,String contactPhone,
			String busImg,String shopImg,
			HttpServletRequest request){
		//String rv = "";
		JsonOutput output = new JsonOutput();

        JSONObject store = new JSONObject();
        //固定参数 "source":2,"status":1,"logo":"","shortName":"","uid":"41572e00edbbfeadb45f1e56",
        if (!StringUtils.isEmpty(baiduUid)) {
        	store.put("baiduUid",baiduUid);
		}
        store.put("source",2);
        store.put("status",1);
        store.put("logo","");
        store.put("shortName","");
        //app传参
        store.put("name",name);
        store.put("tel",tel);
        store.put("busiLicense",busImg);
        store.put("busiImgs",shopImg);
        //门店责任人信息
        JSONObject contactUser = new JSONObject();
        contactUser.put("name",contactName);
        contactUser.put("phone",contactPhone);
        store.put("contactUser",contactUser);
        //门店地址
        JSONObject address = new JSONObject();
        address.put("province",provice);
        address.put("city",city);
        address.put("area",area);
        address.put("address_detail",address_detail);
        JSONArray location = new JSONArray();
        location.add(Double.valueOf(lat));
        location.add(Double.valueOf(lng));
        address.put("location",location);
        store.put("address",address);
        //行业信息格式：
        JSONObject bizClassify = new JSONObject();
		bizClassify.put("id", id1);
		bizClassify.put("name", bizClassify1);
		bizClassify.put("level", 1);
		JSONObject b2 = new JSONObject();
		b2.put("id", id2);
		b2.put("name", bizClassify2);
		b2.put("level", 2);
		JSONObject b3 = new JSONObject();
		b3.put("id", id3);
		b3.put("name", bizClassify3);
		b3.put("level", 3);
		if (id3!=null&&!id3.equals("")) {
			b2.put("childClassify", b3);
		}
		bizClassify.put("childClassify", b2);
		store.put("bizClassify", bizClassify);
		//来源信息
        JSONObject sourceInfo = new JSONObject();
        sourceInfo.put("depName", "代理商平台");//店铺来源为代理商平台
		User user  = userService.getById(userId);
		if (user.getType()==WebConstant.user_type_agent) {
			Agent agent = agentService.getById(user.getTypeId());
			sourceInfo.put("contactor", agent.getContactName());
			sourceInfo.put("tellphone", agent.getContactName());
		}else{
			sourceInfo.put("contactor", "暂无");
		}
		store.put("sourceInfo", sourceInfo);
		store.put("verifyStatus", 1);// 0或1,    表示门店的认证状态，添加时，默认为未认证
		//applicant信息
		JSONObject applicant = new JSONObject();
		applicant.put("id",qualificationId);
		applicant.put("name",name);
		applicant.put("type",2);
		store.put("applicant",applicant);
	    JSONObject data = storeService.addStore(store);
	    if (data != null){
	    	String storeId = data.getString("storeId");
	    	String mcode = data.getString("mcode");
	    	data = storeService.bind(qualificationId, storeId, mcode,CLAIM_STATUS);
	    	//JSONObject rvJSON = JSONObject.parseObject(rv);
	    	if(data != null){
	    		output.setData(data);
	    		output.setMsg("绑定成功！");
	    	}else{
	        	output.setErrCode(BusinessErrorType.MERCHANT_STORE_BIND_ERROR.getErrCode());
	        	output.setMsg(BusinessErrorType.MERCHANT_STORE_BIND_ERROR.getErrMsg());
	    	}
	 	}else{
	    	output.setErrCode(BusinessErrorType.MERCHANT_STORE_ADD_ERROR.getErrCode());
	    	output.setMsg(BusinessErrorType.MERCHANT_STORE_ADD_ERROR.getErrMsg());
		}
		return output.toJSONObject();
	}
	
	/**
	 * 新增并绑定店铺到商户结果页面
	 */
	@RequestMapping("/addAndBindResult")
	public ModelAndView addAndBindResultPage(String qualificationId,String mcode,
			HttpServletRequest request,ModelMap data){
		
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			//获取用户信息
			Integer userId = Integer.parseInt(userToken);
			User user  = userService.getById(userId);
			data.put("user", user);
			data.put("qualificationId", qualificationId);
			data.put("mcode",mcode);
			rv = "/user/merchant/addStore4";
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		return new ModelAndView(rv,data);
	}
	/**
	 * 修改店铺信息
	 * @param request
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public JSONObject updateStore(
			Integer userId,
			String storeId,
			String qualificationId,
			@RequestParam(value = "baiduUid", required = true, defaultValue = "")String baiduUid,
			String name,
			String tel,
			@RequestParam(value = "busImg", required = true, defaultValue = "")String busImg,
			@RequestParam(value = "shopImg", required = true, defaultValue = "")String shopImg,
			String contactName,
			String contactPhone,
			String provice,String city,String area,String address_detail,
			@RequestParam(value = "lng", required = true, defaultValue = "")String lng,
			@RequestParam(value = "lat", required = true, defaultValue = "")String lat,
			String id1,String bizClassify1,String id2,String bizClassify2,
			@RequestParam(value = "id3", required = true, defaultValue = "")String id3,
			@RequestParam(value = "bizClassify3", required = true, defaultValue = "")String bizClassify3,
			HttpServletRequest request){
		JsonOutput output = new JsonOutput();
		try {
			JSONObject store = new JSONObject();
			
			//获取数据

			if (!StringUtils.isEmpty(baiduUid)) {
		    	store.put("baiduUid",baiduUid);
			}
		    store.put("source",2);
		    store.put("status",1);
		    store.put("logo","");
		    store.put("shortName","");
		    //app传参
		    store.put("name",name);
		    store.put("tel",tel);
		    store.put("busiLicense",busImg);
		    store.put("busiImgs",shopImg);
		    //门店责任人信息
		    JSONObject contactUser = new JSONObject();
		    contactUser.put("name",contactName);
		    contactUser.put("phone",contactPhone);
		    store.put("contactUser",contactUser);
		    //门店地址
	        JSONObject address = new JSONObject();
	        address.put("province",provice);
	        address.put("city",city);
	        address.put("area",area);
	        address.put("address_detail",address_detail);
	        JSONArray location = new JSONArray();
	        location.add(Double.valueOf(lat));
	        location.add(Double.valueOf(lng));
	        address.put("location",location);
		    store.put("address",address);
		    //行业信息格式：
	        JSONObject bizClassify = new JSONObject();
			bizClassify.put("id", id1);
			bizClassify.put("name", bizClassify1);
			bizClassify.put("level", 1);
			JSONObject b2 = new JSONObject();
			b2.put("id", id2);
			b2.put("name", bizClassify2);
			b2.put("level", 2);
			JSONObject b3 = new JSONObject();
			b3.put("id", id3);
			b3.put("name", bizClassify3);
			b3.put("level", 3);
			if (id3!=null&&!id3.equals("")) {
				b2.put("childClassify", b3);
			}
			bizClassify.put("childClassify", b2);
		    store.put("bizClassify", bizClassify);
		    //来源信息
	        JSONObject sourceInfo = new JSONObject();
	        sourceInfo.put("depName", "代理商平台");//店铺来源为代理商平台
			User user  = userService.getById(userId);
			if (user.getType()==WebConstant.user_type_agent) {
				Agent agent = agentService.getById(user.getTypeId());
				sourceInfo.put("contactor", agent.getContactName());
				sourceInfo.put("tellphone", agent.getContactName());
			}else{
				sourceInfo.put("contactor", "暂无");
			}
		    store.put("sourceInfo", sourceInfo);
			store.put("verifyStatus", 1);// 0或1,    表示门店的认证状态，添加时，默认为未认证
			//applicant信息
			JSONObject applicant = new JSONObject();
			applicant.put("id",qualificationId);
			applicant.put("name",name);
			applicant.put("type",2);
			store.put("applicant",applicant);
			JSONObject data = storeService.updateStore(store,storeId);
		    if (data != null){
		    	output.setData(data);
		    	output.setMsg("更新店铺信息成功！");
			}else{
			    output.setErrCode(BusinessErrorType.MERCHANT_STORE_UPDATE_ERROR.getErrCode());
			    output.setMsg(BusinessErrorType.MERCHANT_STORE_UPDATE_ERROR.getErrMsg());
			}
		} catch (Exception e) {
			output.setErrCode(BusinessErrorType.MERCHANT_STORE_UPDATE_ERROR.getErrCode());
	    	output.setMsg(BusinessErrorType.MERCHANT_STORE_UPDATE_ERROR.getErrMsg());
			Log.run.error(e.getMessage());
			e.printStackTrace();}
		return output.toJSONObject();
	}
}
